package com.topboya.linker.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.android.flexbox.FlexboxLayout;
import com.topboya.linker.AppConst;
import com.topboya.linker.R;
import com.topboya.linker.diyview.CenteredEditText;
import com.topboya.linker.model.DataManagerbo;
import com.topboya.linker.model.SelectTeamBean;
import com.topboya.linker.model.levelitem.DepartmentGroupBo;
import com.topboya.linker.model.response.DeptUserResponse;
import com.topboya.linker.model.response.FeekbackReponse;
import com.topboya.linker.ui.adapter.RecycleViewDivider;
import com.topboya.linker.ui.adapter.xDeptUserAdapter;
import com.topboya.linker.ui.base.Presenter.BasePresenter;
import com.topboya.linker.ui.base.activity.BaseActivity;
import com.topboya.linker.utils.AndroidUtils;
import com.topboya.linker.utils.LogUtils;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class xSearchTeamActivity extends BaseActivity {

    private static final String TAG = "xSelectTeamActivity:";
    private CenteredEditText search;
    private RecyclerView ry_team;
    private TextView tv_selected_team_num;
    private Toolbar toolbar;
    private TextView toolbar_title;
    private TextView tv_toolbar_right;
    private Button btn_selected;
   private xDeptUserAdapter deptUserAdapter;
//   用来存放搜索出来的数据
   private  List<DepartmentGroupBo> departmetGroupList;
//   获取到组织数据，从头结点开始
   private  List<DepartmentGroupBo> departmentGroupBosroot;
   private SelectTeamBean selectTeamBean;
    //     用来保存已经选中的人员
    private LinkedHashMap<String ,DepartmentGroupBo> selectedDepartLinkHashList = new LinkedHashMap<>();

    @Override
    protected int getLayoutId() {

        return R.layout.activity_search_team;
    }

    @Override
    protected void initView() {

        toolbar = findViewById(R.id.toolbar);
        toolbar_title = findViewById(R.id.toolbar_title);
        tv_toolbar_right = findViewById(R.id.tv_toolbar_right);
        search = findViewById(R.id.search);
        ry_team = findViewById(R.id.ry_team);
        tv_selected_team_num = findViewById(R.id.tv_selected_team_num);
        btn_selected = findViewById(R.id.btn_selected);
        initTitle();
    }

    private void initTitle() {

        toolbar_title.setText("选择人员");
        tv_toolbar_right.setVisibility(View.GONE);

    }

    @Override
    protected void initData() {

        departmentGroupBosroot = (List<DepartmentGroupBo>) getIntent().getSerializableExtra("departmentGroupBosroot");

        selectTeamBean = (SelectTeamBean) getIntent().getSerializableExtra("selectTeamBean");
        if (null !=selectTeamBean ){

            selectedDepartLinkHashList.clear();
            selectedDepartLinkHashList.putAll(selectTeamBean.getSelectedDepartLinkHashList());
        }
        departmetGroupList = new ArrayList<>();
        tv_selected_team_num.setText("已选择："+getDepartmentGroupBos().size()+"人");
        initRcyView();


}

    private void initRcyView() {

        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        ry_team.setLayoutManager(layoutManager);
        ry_team.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.HORIZONTAL, 2, 0xBFC0C2));

        deptUserAdapter = new xDeptUserAdapter(departmetGroupList);
        ry_team.setAdapter(deptUserAdapter);
    }


    public static void hideKeyboard(View view) {

        InputMethodManager manager = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        manager.hideSoftInputFromWindow(view.getWindowToken(), 0);

    }
    @Override
    protected void initListener() {

        toolbar.setNavigationOnClickListener(v -> { back();});
        search.setOnEditorActionListener((v, actionId, event) ->{

            String searchKey =  v.getText().toString().trim();
            hideKeyboard(search);
            searchName(searchKey);
            return false;

        });


        deptUserAdapter.setOnItemClickListener((adapter, view, position) -> { setSelectData(position); });

        deptUserAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            switch (view.getId()){

                case R.id.ck_select:

                    setSelectData(position);

                    break;
            }
        });
        btn_selected.setOnClickListener(v -> {

//          得到根节点；开始遍历成员为true的
            ArrayList<DepartmentGroupBo> selectdepts = getDepartmentGroupBos();
            LogUtils.v(TAG+"getDeparemtname()"+selectdepts.toString());
            //数据是使用Intent返回
            Intent intent = new Intent(xSearchTeamActivity.this,xMainActivity.class);
            intent.putExtra("isfeedback",true);
            AppConst.SELECTED_MEMBER = selectdepts;
            //设置返回数据
            startActivity(intent);

        });

    }

    @NonNull
    private ArrayList<DepartmentGroupBo> getDepartmentGroupBos() {
        ArrayList<DepartmentGroupBo> selectdepts = new ArrayList();
        selectdepts.clear();
        for (Map.Entry<String,DepartmentGroupBo> entry : selectedDepartLinkHashList.entrySet()) {

            DepartmentGroupBo productDetailInfoList = entry.getValue();
            if (!productDetailInfoList.isSub()){
                selectdepts.add(productDetailInfoList);
            }
        }
        return selectdepts;
    }


    public void setSelectData(int position){

        DepartmentGroupBo departmentGroupBo = selectedDepartLinkHashList.get(departmetGroupList.get(position).getMemberID());
        if (null==departmentGroupBo){

            selectedDepartLinkHashList.put(departmetGroupList.get(position).getMemberID(),departmetGroupList.get(position));
        }else {

            selectedDepartLinkHashList.remove(departmentGroupBo.getMemberID());
        }
        tv_selected_team_num.setText("已选择："+getDepartmentGroupBos().size()+"人");

    }


    private void searchName(String searchKey) {

        departmetGroupList.clear();
        getAllSearchDepts(departmentGroupBosroot,departmetGroupList,searchKey);
        deptUserAdapter.setSelectDepartLinkHash(selectedDepartLinkHashList);
        deptUserAdapter.setNewData(departmetGroupList);
        LogUtils.v(TAG + "selectdepts:"+departmetGroupList.toString());

    }

    public  void getAllSearchDepts(List<DepartmentGroupBo> departmentGroupBo,List<DepartmentGroupBo> selectdepts,String searchKey){

        for (DepartmentGroupBo departmentGroup: departmentGroupBo) {

            if (!departmentGroup.isSub() && departmentGroup.getDeparemtname().contains(searchKey)){
                selectdepts.add(departmentGroup);
            }
            getAllSearchDepts(departmentGroup.getDepartmentGroupBosCd(),selectdepts,searchKey);

        }

    }





    @Override
    protected BasePresenter createPresenter() {

        return null;
    }



    @Override
    public void onBackPressed() {

        back();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 是否触发按键为back键
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed();
            return true;
        } else { // 如果不是back键正常响应
            return super.onKeyDown(keyCode, event);
        }
    }

    private void back() {

        Intent intent = new Intent();
        SelectTeamBean selectTeamBean = new SelectTeamBean();
        selectTeamBean.setSelectedDepartLinkHashList(selectedDepartLinkHashList);
        //把返回数据存入Intent
        intent.putExtra("selectTeamBean", selectTeamBean);
        //设置返回数据
        setResult(1002, intent);
        //关闭Activity
        finish();

    }



}
